<template>
  <!-- threejs -->
  <div
    id="container"
    style="position: fixed; left: 0px; z-index: 1; width: 80vw"
  ></div>
  <!-- 视频 -->
  <video
    class="lib-video vjs-hidden"
    style="position: fixed; left: 0px; z-index: 0; "
    id="J_Video_Player"
    poster=""
    muted="false"
    src=""
    width="100%"
  >
    <source src="../../public/sintel.mp4" type="video/mp4" />
  </video>
  <button
    id="sendMessageBtn"
    style="position: fixed; left: 0px; z-index: 10000; display: block"
  >
    跳转页面
  </button>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import Stats from "three/addons/libs/stats.module.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { Water } from "three/addons/objects/Water.js";
import { Sky } from "three/addons/objects/Sky.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { RGBELoader } from "three/addons/loaders/RGBELoader.js";

import * as THREE from "three";
// 导入Tween.js
// import * as TWEEN from "@tweenjs/tween.js";

let container;
let stats;
let camera, scene, renderer;
let controls, water, sun, mesh;
let video, videoTexture, sky;
const BASE_URL = "../../public";
let VideoPlayer = lib.videoPlayer;
let myPlayer = null;
let model = null;
let tower = null;
let yellowFloors = [];
let textures = reactive({
  texture1: null,
  texture2: null,
  texture3: null,
  texture4: null,
  texture1_1: null,
  texture2_1: null,
  texture3_1: null,
  texture4_1: null,
});

let enableTouch = ref(false);
let loadFinish = ref(false);

onMounted(async () => {
  phoneStyle();
  container = document.getElementById("container");
  myPlayer = VideoPlayer("J_Video_Player", {
    "custom-controls": "false", //隐藏底部控制栏
  });

  myPlayer.on("video:ended", () => {
    //监听视频结束事件
    myPlayer.play();
  });

  // const sendMessageBtn = document.getElementById("sendMessageBtn");
  // sendMessageBtn.onclick = () => {
  //   if (!loadFinish.value) return;
  //   wx.miniProgram.postMessage({ data: "foo" });
  //   wx.miniProgram.navigateTo({ url: "/pages/test/test" });
  // };

  window.addEventListener("hashchange", onHashChange);

  await init();
  animate();
  setTimeout(() => {
    myPlayer.play();
    panoramaAnimate();
    phoneType.value? touchEventPhone(): touchEventPc();
    // 测试
    // clickEvent();
  }, 20);
});

onUnmounted(() => {
  window.removeEventListener("hashchange", onHashChange);
  window.removeEventListener("resize", onWindowResize);
});
const phoneType=ref(false)
function phoneStyle() {
  // 检查navigator.userAgent以确定设备类型
  const userAgentInfo = navigator.userAgent;
  const agents = ["Android", "iPhone", "iPad", "iPod"];

   phoneType.value = false;
  for (let i = 0; i < agents.length; i++) {
    if (userAgentInfo.indexOf(agents[i]) > 0) {
      phoneType.value = true;
      break;
    }
  }

}

function onHashChange() {
  console.log("Hash changed to " + window.location.hash);
  // 定位到第二栋楼
  if (!loadFinish.value) return;

  const video = myPlayer.getVideoEl();
  closeVolume(video);
  myPlayer.play();

  highLight(1, -16);
}

function closeVolume(dom) {
  dom.volume = 0;
  dom.muted = true;
}

function openVolume(dom) {
  dom.volume = 1;
  dom.muted = false;
}

async function init() {
  // 渲染器
  initRender();
  // 相机
  initCamera();

  // 加载器
  await initLoader();
  console.log(model, "8888888888sss  2222");

  // Water
  addWater();
  // Skybox
  addSkyBox();
  // sun
  updateSun();
  // 控制器
  updateControls();

  window.addEventListener("resize", onWindowResize);
  setTimeout(() => {
    loadFinish.value = true;
    getYellowFloor();
  }, 0);
  // setTimeout(() => {
  //   loadFinish.value = true;
  //   getYellowFloor();
  // }, 4000);
}

function highLight(index, targetX) {
  //让所有黄色楼边黑
  yellowFloors.forEach((item) => {
    new TWEEN.Tween(item.material)
      .to({ opacity: 0 }, 500)
      .start()
      .easing(TWEEN.Easing.Sinusoidal.InOut);
  });

  //  让当前楼变黄
  new TWEEN.Tween(yellowFloors[index].material)
    .to({ opacity: 1 }, 800)
    .start()
    .easing(TWEEN.Easing.Sinusoidal.InOut);

  // model位置改变
  new TWEEN.Tween(model.position)
    .to({ x: targetX }, 800)
    .onComplete(() => {
      enableTouch.value = true;
    })
    .start()
    .easing(TWEEN.Easing.Sinusoidal.InOut);
}

// 初始化渲染器
function initRender() {
  scene = new THREE.Scene();
  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio(window.devicePixelRatio);
  console.log(window.innerWidth, window.innerHeight,'window.innerWidth' )
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 0.6;
  console.log(renderer.domElement, "renderer.domElement");
  container.appendChild(renderer.domElement);
}
// 初始化相机
function initCamera() {
  camera = new THREE.PerspectiveCamera(
    55,
    window.innerWidth / window.innerHeight,
    1,
    20000
  );
  camera.position.set(0, 0, 1000);
}

async function loadHDRTexture(url) {
  return new Promise((resolve, reject) => {
    new RGBELoader().load(
      url,
      (texture) => resolve(texture),
      undefined,
      (error) => reject(error)
    );
  });
}

async function loadGLTFModel(url) {
  return new Promise((resolve, reject) => {
    new GLTFLoader().load(
      url,
      (gltf) => resolve(gltf),
      undefined,
      (error) => reject(error)
    );
  });
}

async function initLoader() {
  try {
    // Asynchronously load the HDR texture
    const texture = await loadHDRTexture(BASE_URL + "/royal_esplanade_1k.hdr");
    texture.mapping = THREE.EquirectangularReflectionMapping;
    scene.background = texture;
    scene.environment = texture;
    // Asynchronously load the GLTF model
    const gltf = await loadGLTFModel(BASE_URL + "/tower-no.glb");
    // Initialize the model
    await initModel(gltf);

    // Create the template tower
    initTempTower();

    // Clone a tower (black)
    cloneTower(
      "Genius_City_BG_Tower_1_DEMO",
      "Genius_City_BG_Tower_1_DEMO_0_black",
      0,
      -1,
      true
    );

    // Clone the tower with video
    await addVideoFloor();

    // 克隆其余的楼
    for (let i = 0; i < 9; i++) {
      let num = Number(i);
      // 黑色楼
      cloneTower(
        "Genius_City_BG_Tower_1_DEMO",
        "Genius_City_BG_Tower_1_DEMO" + "_" + (i + 1) + "_black",
        (i + 1) * 8,
        -(i + 1),
        true
      );
      // 黄色楼
      cloneTower(
        "Genius_City_BG_Tower_1_DEMO",
        "Genius_City_BG_Tower_1_DEMO" + "_" + (i + 1),
        (i + 1) * 8,
        -(i + 1)
      );
    }
    render();
  } catch (error) {}
}

// initModel
async function initModel(gltf) {
  // 黑色建筑
  model = gltf.scene;
  model.position.x -= 40;
  model.rotation.y += Math.PI;
  await renderer.compileAsync(model, camera, scene);
  scene.add(model);
}

// 初始化城市
function initTempTower() {
  console.log("initTempTower");
  textures.texture1 = new THREE.TextureLoader().load(
    BASE_URL + "/BG_Tower_1_Diffuse_1KJ.png"
  );
  textures.texture1.colorSpace = THREE.SRGBColorSpace;

  textures.texture2 = new THREE.TextureLoader().load(
    BASE_URL + "/BG_Tower_1_Roughness_1K.png"
  );
  textures.texture2.colorSpace = THREE.SRGBColorSpace;

  textures.texture3 = new THREE.TextureLoader().load(
    BASE_URL + "/BG_Tower_1_Normal_1K.png"
  );
  textures.texture3.colorSpace = THREE.SRGBColorSpace;

  textures.texture4 = new THREE.TextureLoader().load(
    BASE_URL + "/BG_Tower_1_Emission_1K.png"
  );
  textures.texture4.colorSpace = THREE.SRGBColorSpace;

  textures.texture1_1 = new THREE.TextureLoader().load(
    BASE_URL + "/word_BAKE_BaseColor.png"
  );
  textures.texture1_1.colorSpace = THREE.SRGBColorSpace;

  textures.texture2_1 = new THREE.TextureLoader().load(
    BASE_URL + "/word_BAKE_Roughness.png"
  );
  textures.texture2_1.colorSpace = THREE.SRGBColorSpace;

  textures.texture3_1 = new THREE.TextureLoader().load(
    BASE_URL + "/word_BAKE_Normal.png"
  );
  textures.texture3_1.colorSpace = THREE.SRGBColorSpace;

  textures.texture4_1 = new THREE.TextureLoader().load(
    BASE_URL + "/word_BAKE_Emissive.png"
  );
  textures.texture4_1.colorSpace = THREE.SRGBColorSpace;
  console.log(model, "llllmodel");
  // 大楼模板
  tower = model.getObjectByName("Genius_City_BG_Tower_1_DEMO");

  let tmpArray = tower.geometry.attributes.uv.array;
  for (let i = 0; i < tmpArray.length / 2; i++) {
    tmpArray[i * 2 + 1] = 1.0 - tmpArray[i * 2 + 1];
  }
  tower.geometry.attributes.uv.array = tmpArray;
  tower.geometry.attributes.uv.needsUpdate = true;
  tower.material.map = textures.texture1;
  tower.material.roughnessMap = textures.texture2;
  tower.material.normalMap = textures.texture3;
  tower.material.emissiveMap = textures.texture4;
}

// getYellowFloor
function getYellowFloor() {
  console.log(scene, "scenescenescenescenescene");
  // 获取所有黄色贴图楼
  yellowFloors = [];
  for (let i = 0; i < 10; i++) {
    for (let item of scene.children[0].children) {
      if (item.name == `Genius_City_BG_Tower_1_DEMO_${i}`) {
        yellowFloors.push(item);
      }
    }
  }
  console.log(scene, "################### cccc", yellowFloors);
}

// 添加视频层
function addVideoFloor() {
  // 第二栋楼
  let addTowerVideo = cloneTower(
    "Genius_City_BG_Tower_1_DEMO",
    "Genius_City_BG_Tower_1_DEMO_0",
    0,
    -1
  );
  console.log(THREE.DoubleSide, "THREE.DoubleSide ", addTowerVideo);
  setTimeout(() => {
    let material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide });
    addTowerVideo.material = material;
    addTowerVideo.material.transparent = true;
    addTowerVideo.material.opacity = 1;
    let videoTexture = createVideoTexture();
    addTowerVideo.material.map = videoTexture;
    window.addTowerVideo = addTowerVideo;
  }, 500);
}
// 创建视频纹理
function createVideoTexture() {
  console.log(myPlayer, "myPlayermyPlayermyPlayermyPlayer");
  let video = myPlayer.getVideoEl();
  closeVolume(video);
  myPlayer.play();
  videoTexture = new THREE.VideoTexture(video);
  videoTexture.colorSpace = THREE.SRGBColorSpace;
  return videoTexture;
}
// 克隆楼
function cloneTower(source, name, x, z, isBlack = false) {
  const initX = 8.0;
  var tower_clone = model.getObjectByName(source).clone();
  tower_clone.name = name;

  // 材质替换就可以
  tower_clone.material = tower.material.clone();
  tower_clone.material.transparent = true;
  tower_clone.material.opacity = 1;

  tower.parent.add(tower_clone);
  tower_clone.position.x -= initX + x;

  if (!isBlack) {
    tower_clone.material.map = textures.texture1_1;
    tower_clone.material.metalnessMap = textures.texture2_1;
    tower_clone.material.roughnessMap = textures.texture2_1;
    tower_clone.material.normalMap = textures.texture3_1;
    tower_clone.material.emissiveMap = textures.texture4_1;
    tower_clone.material.needsUpdate = true;
  }
  return tower_clone;
}

// onWindowResize
function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

// 添加水体
function addWater() {
  water = new Water(new THREE.PlaneGeometry(10000, 10000), {
    textureWidth: 512,
    textureHeight: 512,
    waterNormals: new THREE.TextureLoader().load(
      BASE_URL + "/waternormals.jpg",
      (texture) => {
        texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
      }
    ),
    alpha: 1.0,
    sunDirection: new THREE.Vector3(),
    sunColor: 0xffffff,
    waterColor: 0x001e0f,
    distortionScale: 3.7,
    fog: scene.fog !== undefined,
  });

  water.rotation.x = -Math.PI / 2;
  scene.add(water);
}

// 添加天空盒
function addSkyBox() {
  sky = new Sky();
  sky.scale.setScalar(10000);
  scene.add(sky);

  const skyUniforms = sky.material.uniforms;

  skyUniforms["turbidity"].value = 10;
  skyUniforms["rayleigh"].value = 2;
  skyUniforms["mieCoefficient"].value = 0.005;
  skyUniforms["mieDirectionalG"].value = 0.8;
}

// 更新太阳位置
function updateSun() {
  sun = new THREE.Vector3();
  const pmremGenerator = new THREE.PMREMGenerator(renderer);
  const parameters = {
    elevation: -3, //时间
    azimuth: -28,
  };
  const sceneEnv = new THREE.Scene();
  const phi = THREE.MathUtils.degToRad(90 - parameters.elevation);
  const theta = THREE.MathUtils.degToRad(parameters.azimuth);
  let renderTarget;

  sun.setFromSphericalCoords(1, phi, theta);

  sky.material.uniforms["sunPosition"].value.copy(sun);
  water.material.uniforms["sunDirection"].value.copy(sun).normalize();

  if (renderTarget !== undefined) renderTarget.dispose();

  sceneEnv.add(sky);
  renderTarget = pmremGenerator.fromScene(sceneEnv);
  scene.add(sky);

  scene.environment = renderTarget.texture;
}

// 更新控制器
function updateControls() {
  console.log(renderer.domElement, camera, "renderer.domElement1111");

  controls = new OrbitControls(camera, renderer.domElement);
  controls.enableRotate = false; // 禁用旋转
  controls.maxPolarAngle = Math.PI * 0.495;
  controls.target.set(0, 10, 0);
  controls.minDistance = 40.0;
  controls.maxDistance = 200.0;
  controls.update();
}

// 全景动画
function panoramaAnimate() {
  new TWEEN.Tween(model.position)
    .to({ x: 0 }, 1500)
    .start()
    .easing(TWEEN.Easing.Sinusoidal.InOut);

  new TWEEN.Tween(controls.object.position)
    .to({ z: 40 }, 1500)
    .onComplete(() => {
      console.log("onCompleteonComplete");

      enableTouch.value = true;
    })

    .start()
    .easing(TWEEN.Easing.Sinusoidal.InOut);
  console.log("ssssssssss");

  // 让所有黄色楼边黑
  for (let item of yellowFloors) {
    new TWEEN.Tween(item.material)
      .to({ opacity: 0 }, 1500)
      .start()
      .easing(TWEEN.Easing.Sinusoidal.InOut);
  }
}

// touchEventPc
function touchEventPc() {
  console.log(container, "loooooooooooooooooo");
  let startX = 0;
  let endX = 0;
  // touchstart
  container.addEventListener("mousedown", function (event) {
    console.log(enableTouch.value, "1111111111111111111111111111");
    console.log(event, event.pageX, "event.touchesevent.touches");
    // if (!enableTouch.value) return;
    event.preventDefault();
    startX = event.pageX;
    console.log("touchstart_____", startX);
  });
  // touchend
  container.addEventListener("mouseup", function (event) {
    console.log(
      enableTouch.value,
      "1111111111111111111111111111222222222222222222"
    );

    console.log("touchend_____11");

    // if (!enableTouch.value) return;
    console.log("touchend_____");
    enableTouch.value = false;
    event.preventDefault();
    endX = event.pageX;
    let detalX = endX - startX;
    console.log("detalX_______", detalX);
    console.log(endX, startX, "startXstartXstartX");
    let step = 0;
    if (Math.abs(detalX) <= 100) {
      step = 0;
    } else if (Math.abs(detalX) > 100 && Math.abs(detalX) <= 200) {
      step = 1;
    } else if (Math.abs(detalX) > 200 && Math.abs(detalX) <= 300) {
      step = 2;
    } else if (Math.abs(detalX) > 300 && Math.abs(detalX) <= 400) {
      step = 3;
    } else {
      step = 3;
    }

    console.log("step==========", step, detalX);

    if (detalX > 0) {
      console.log("左移", model.position.x);
      if (model.position.x >= 0) return (enableTouch.value = true);

      // 根据移动的距离判断哪栋楼该贴黄色贴图
      // console.log(Math.abs(model.position.x) / 8)
      let currentIndex = Math.abs(model.position.x) / 8 - step;
      currentIndex = currentIndex < 1 ? 1 : currentIndex;

      console.log("currentIndex", currentIndex);

      // 让全部得楼变黑
      for (let item of yellowFloors) {
        new TWEEN.Tween(item.material)
          .to({ opacity: 0 }, 800)
          .start()
          .easing(TWEEN.Easing.Sinusoidal.InOut);
      }

      // 让当前楼变黄 最大currentIndex是10
      if (currentIndex - 2 >= 0) {
        if (
          yellowFloors[currentIndex - 2] &&
          yellowFloors[currentIndex - 2].material
        ) {
          const tween1 = new TWEEN.Tween(
            yellowFloors[currentIndex - 2].material
          )
            .to({ opacity: 1 }, 800)
            .start()
            .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动
        }
      }

      // 改变model移动距离
      let x = model.position.x + 8 * (step + 1);

      console.log("x", x);

      const tween3 = new TWEEN.Tween(model.position)
        .to({ x: currentIndex == 1 ? 0 : x }, 800)
        .onComplete(() => {
          enableTouch.value = true;
        })
        .start()
        .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动
    } else if (detalX < 0) {
      console.log("右移", model.position.x);
      if (model.position.x < -72) return (enableTouch.value = true);

      // 根据移动的距离判断哪栋楼该贴黄色贴图
      // console.log(Math.abs(model.position.x) / 8)

      let currentIndex = 0;
      if (Math.abs(model.position.x == 0)) {
        currentIndex = step;
      } else {
        currentIndex = Math.abs(model.position.x) / 8 + step;
        currentIndex = currentIndex > 9 ? 9 : currentIndex;
      }

      console.log("currentIndex", currentIndex);

      // 让全部得楼变黑
      for (let item of yellowFloors) {
        new TWEEN.Tween(item.material)
          .to({ opacity: 0 }, 800)
          .start()
          .easing(TWEEN.Easing.Sinusoidal.InOut);
      }

      // 让当前楼变黄
      const tween1 = new TWEEN.Tween(yellowFloors[currentIndex].material)
        .to({ opacity: 1 }, 800)
        .start()
        .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动

      // model位置改变
      let x = model.position.x - 8 * (step + 1);
      const tween = new TWEEN.Tween(model.position)
        .to({ x: currentIndex == 9 ? -80 : x }, 800)
        .onComplete(() => {
          enableTouch.value = true;
        })
        .start()
        .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动
    }
  });
}

function touchEventPhone() {
  console.log(container, "loooooooooooooooooo");
  let startX = 0;
  let endX = 0;
  // touchstart
  container.addEventListener("touchstart", function (event) {
    console.log(enableTouch.value, "1111111111111111111111111111");
    console.log(event, event.pageX, "event.touchesevent.touches");
    if (!enableTouch.value) return;
    event.preventDefault();
    startX = event.touches[0].pageX;
    console.log("touchstart_____", startX);
  });
  // touchend
  container.addEventListener("touchend", function (event) {
    console.log(
      enableTouch.value,
      "1111111111111111111111111111222222222222222222"
    );

    console.log("touchend_____11");

    if (!enableTouch.value) return;
    console.log("touchend_____");
    enableTouch.value = false;
    event.preventDefault();
    endX = event.changedTouches[0].pageX;
    let detalX = endX - startX;
    console.log("detalX_______", detalX);
    console.log(endX, startX, "startXstartXstartX");
    let step = 0;
    if (Math.abs(detalX) <= 100) {
      step = 0;
    } else if (Math.abs(detalX) > 100 && Math.abs(detalX) <= 200) {
      step = 1;
    } else if (Math.abs(detalX) > 200 && Math.abs(detalX) <= 300) {
      step = 2;
    } else if (Math.abs(detalX) > 300 && Math.abs(detalX) <= 400) {
      step = 3;
    } else {
      step = 3;
    }

    console.log("step==========", step, detalX);

    if (detalX > 0) {
      console.log("左移", model.position.x);
      if (model.position.x >= 0) return (enableTouch.value = true);

      // 根据移动的距离判断哪栋楼该贴黄色贴图
      // console.log(Math.abs(model.position.x) / 8)
      let currentIndex = Math.abs(model.position.x) / 8 - step;
      currentIndex = currentIndex < 1 ? 1 : currentIndex;

      console.log("currentIndex", currentIndex);

      // 让全部得楼变黑
      for (let item of yellowFloors) {
        new TWEEN.Tween(item.material)
          .to({ opacity: 0 }, 800)
          .start()
          .easing(TWEEN.Easing.Sinusoidal.InOut);
      }

      // 让当前楼变黄 最大currentIndex是10
      if (currentIndex - 2 >= 0) {
        if (
          yellowFloors[currentIndex - 2] &&
          yellowFloors[currentIndex - 2].material
        ) {
          const tween1 = new TWEEN.Tween(
            yellowFloors[currentIndex - 2].material
          )
            .to({ opacity: 1 }, 800)
            .start()
            .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动
        }
      }

      // 改变model移动距离
      let x = model.position.x + 8 * (step + 1);

      console.log("x", x);

      const tween3 = new TWEEN.Tween(model.position)
        .to({ x: currentIndex == 1 ? 0 : x }, 800)
        .onComplete(() => {
          enableTouch.value = true;
        })
        .start()
        .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动
    } else if (detalX < 0) {
      console.log("右移", model.position.x);
      if (model.position.x < -72) return (enableTouch.value = true);

      // 根据移动的距离判断哪栋楼该贴黄色贴图
      // console.log(Math.abs(model.position.x) / 8)

      let currentIndex = 0;
      if (Math.abs(model.position.x == 0)) {
        currentIndex = step;
      } else {
        currentIndex = Math.abs(model.position.x) / 8 + step;
        currentIndex = currentIndex > 9 ? 9 : currentIndex;
      }

      console.log("currentIndex", currentIndex);

      // 让全部得楼变黑
      for (let item of yellowFloors) {
        new TWEEN.Tween(item.material)
          .to({ opacity: 0 }, 800)
          .start()
          .easing(TWEEN.Easing.Sinusoidal.InOut);
      }

      // 让当前楼变黄
      const tween1 = new TWEEN.Tween(yellowFloors[currentIndex].material)
        .to({ opacity: 1 }, 800)
        .start()
        .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动

      // model位置改变
      let x = model.position.x - 8 * (step + 1);
      const tween = new TWEEN.Tween(model.position)
        .to({ x: currentIndex == 9 ? -80 : x }, 800)
        .onComplete(() => {
          enableTouch.value = true;
        })
        .start()
        .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动
    }
  });
}

function clickEvent(event) {
  const raycaster = new THREE.Raycaster();
  const mouse = new THREE.Vector2();
  document.addEventListener(
    "mousedown",
    (event) => {
      event.preventDefault();
      // 将鼠标位置转换成归一化设备坐标(-1 到 +1)
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
      const point = {
        x: mouse.x,
        y: mouse.y,
      };
      // 使用鼠标位置和相机进行射线投射
      raycaster.setFromCamera(mouse, camera);

      // 计算物体和射线的交点
      const intersects = raycaster.intersectObjects(scene.children);

      // 如果有交点
      if (intersects.length > 0) {
        // 获取第一个交点的对象
        console.log(intersects, "intersects");
        const intersection = intersects[0];

        // 你可以访问intersection.object来获取点击的模型对象
        console.log(intersection.object, "yellowFloors模型对象");

        // 你也可以获取点击的坐标等信息
        console.log("Clicked at:", intersection.point);

        // 在这里处理点击模型后的逻辑
        clickModelIsYellow(intersection.object);
      }
    },
    false
  );
}
const clickModelIsYellow = (modelObject) => {
  console.log(modelObject, "modelObject.material");
  console.log(yellowFloors, "yellowFloorsccccccccc1111");

  // 让全部得楼变黑
  for (let item of yellowFloors) {
    new TWEEN.Tween(item.material)
      .to({ opacity: 0 }, 800)
      .start()
      .easing(TWEEN.Easing.Sinusoidal.InOut);
  }
  console.log(yellowFloors, "yellowFloorsccccccccc2222sss", modelObject);
  const itemIndex = yellowFloors.findIndex(
    (i) => i.name === modelObject.name.split("_").slice(0, -1).join("_")
  );
  console.log(itemIndex, "itemIndex");
  if (itemIndex === -1) return;
  console.log(yellowFloors[4].material, "########", modelObject.material);
  // 让当前楼变黄
  const tween1 = new TWEEN.Tween(yellowFloors[itemIndex]?.material)
    .to({ opacity: 1 }, 800)
    .start()
    .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动
  // model位置改变
  let x = model.position.x;
  let y = model.position.y;
  const tween = new TWEEN.Tween(model.position)
    .to({ x: x, y: y }, 800)
    .onComplete(() => {
      enableTouch.value = true;
    })

    .start()
    .easing(TWEEN.Easing.Sinusoidal.InOut); //进入和结束都设置缓动
};
// 动画
async function animate() {
  requestAnimationFrame(animate);
  render();
  TWEEN.update();
}

async function render() {
  const time = performance.now() * 0.001;
  if (water && water.material) {
    water.material.uniforms["time"].value += 1.0 / 60.0;
  }
  renderer.render(scene, camera);
}
</script>
